package com.edu.examhelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.PublicKey;

import net.youmi.android.AdManager;
import net.youmi.android.banner.AdSize;
import net.youmi.android.banner.AdView;
import net.youmi.android.offers.OffersManager;

import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Color;
import android.view.MotionEvent;

import com.umeng.fb.FeedbackAgent;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.analytics.MobclickAgent;

public class ExamHelper extends Activity {
	/** Called when the activity is first created. */
	public static final int OPTION_TEST = 3;//模拟考试
	public static final int MODE = MODE_PRIVATE;
	public static final String PREFERENCE_NAME = "SaveSetting";//保存设置
	public static final String CONFIG_COURSENAME = "";//课程名称,c0,vb1,vfp2;
	public static final String CONFIG_AUTOCHECK = "config_autocheck";//自动确认
	public static final String CONFIG_AUTO2NEXT = "config_auto2next";//答对后自动跳转下一题
	public static final String CONFIG_AUTO2ADDWRONGSET = "config_auto2addwrongset";//自动加入错题库
	

	LinearLayout btn_test;
	LinearLayout btn_MyCourse;

	
	private Button btn_onlineanswer = null;
	private Button btn_about = null;
	private ProgressDialog mProgressDialog = null;
	private int TEST_BELONG;
	private int mTotalCount = 0;//试题总数
	//友盟信息反馈
	FeedbackAgent mAgent;
	Dialog dialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//友盟自动更新功能
		UmengUpdateAgent.update(this);
		
		setContentView(R.layout.menu);
		btn_test = (LinearLayout) findViewById(R.id.btn_test);
		btn_MyCourse = (LinearLayout) findViewById(R.id.btn_MyCourse);
		btn_about = (Button) findViewById(R.id.btn_about);
		btn_onlineanswer = (Button) findViewById(R.id.btn_onlineanswer);
		

		btn_MyCourse.setOnTouchListener(otl4);
		
		//以下为有米广告
		 // 初始化应用的发布ID和密钥，以及设置测试模式5a4522d4f966fc95,1bdb75e63caae0e0
       AdManager.getInstance(this).init("5a4522d4f966fc95","1bdb75e63caae0e0", false); 
		OffersManager.getInstance(this).onAppLaunch();
       //有米广告结束
		
		// !!!!!!!!sharedPreferencesInit();//!!!!!!!!!!!!!!!!!!初始配置
		SharedPreferences sharedPreferences = getSharedPreferences(
				PREFERENCE_NAME, MODE);
		
		judgeTheFirstTime2Run();
		
		//友盟反馈
		mAgent = new FeedbackAgent(this);
		mAgent.sync();
		
		
		
		

		
		/*
		 * 模拟考试
		 */
		
		btn_test.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//初始化试卷
				SharedPreferences sharedPreferences = getSharedPreferences(
						ExamHelper.PREFERENCE_NAME, ExamHelper.MODE);
				String COURSENAME = sharedPreferences.getString(ExamHelper.CONFIG_COURSENAME, "");
				
				//如果没有选择课程，则提示
				if (COURSENAME=="") {
					AlertDialog.Builder builder = new Builder(ExamHelper.this);
					builder.setMessage("请先添加课程");

					builder.setTitle("提示");

					builder.setPositiveButton("确认",
							new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface v, int which) {
									// TODO Auto-generated method stub
									startActivity(new Intent().setClass(ExamHelper.this,
											MyCourse.class));
									
								}
							});
					builder.create().show();
				}
				else{
					startActivity(new Intent().setClass(ExamHelper.this,
						ExamActivity.class));
				}
			}
		});
		/*
		 * 我的课程
		 */
		btn_MyCourse.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//我的课程
				startActivity(new Intent().setClass(ExamHelper.this,
						MyCourse.class));	
			}
		});
	
		btn_onlineanswer.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//友盟在线提问
				mAgent.startFeedbackActivity();
			}
		});

		btn_about.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				aboutdialog();	
			}
		});
		
	}
	
	public OnTouchListener otl3 = new OnTouchListener() {

		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				btn_test.setBackgroundColor(Color.rgb(127, 127, 127));
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				btn_test.setBackgroundColor(Color.TRANSPARENT);
			}
			return false;
		}
	};

	public OnTouchListener otl4 = new OnTouchListener() {

		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				btn_MyCourse.setBackgroundColor(Color.rgb(127, 127, 127));
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				btn_MyCourse.setBackgroundColor(Color.TRANSPARENT);
			}
			return false;
		}
	};


    /** 
     * 用Handler来更新UI 
     */  
    private Handler handler = new Handler(){  
  
        @Override  
        public void handleMessage(Message msg) {      	
            //关闭ProgressDialog  
            mProgressDialog.dismiss();
            Toast.makeText(getApplicationContext(), "试题加载完成", Toast.LENGTH_SHORT).show();
        }};  
	
	private void judgeTheFirstTime2Run() {
		// TODO Auto-generated method stub
		DBAdapter dbAdapter;
		Cursor cursor;
		try {
			dbAdapter = new DBAdapter(this);
			dbAdapter.open();
			cursor = dbAdapter.getAllData();
			
			if (cursor.getCount() == 0) {		
				mProgressDialog = new ProgressDialog(this);
				//设置进度条风格，风格为长形，有刻度的
				mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				//设置ProgressDialog 标题
				mProgressDialog.setTitle("大学题库");
				//设置ProgressDialog 提示信息
				mProgressDialog.setMessage("试题加载中……");
				//设置ProgressDialog 是否可以按退回按键取消
				mProgressDialog.setCancelable(false);			
				mProgressDialog.show();
				new Thread(){
					@Override 
					public void run() {
						mTotalCount = GetTestCount();
						DataTrans();
						InitDBCourse();//初始化数据库中course表
						handler.sendEmptyMessage(0); 
					}
				}.start();
			}
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(this, "加载失败，请重新运行程序！", Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			exitdialog();
		}
		return false;
	}
	@Override  
    protected void onDestroy() {  
        super.onDestroy();   
		OffersManager.getInstance(this).onAppExit();
    }  
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);//友盟统计分析
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);//友盟统计分析
	}

	protected void exitdialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确认退出吗？");

		builder.setTitle("提示");

		builder.setPositiveButton("确认",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface v, int which) {
						// TODO Auto-generated method stub
						finish();
						
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	protected void aboutdialog() {
		
		String copyright;
		AlertDialog.Builder builder = new Builder(this);
		copyright = "大学题库考试系统，包括历年真题练习，在线提问等功能\n邮箱：ncrehelper@sina.com\nCopyright©2013 Wisdom Education\nAll Rights Reserved 慧育科技";
		builder.setMessage(copyright);

		builder.setTitle("关于");

		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		builder.create().show();
	}
	//得到试题总数
	public int GetTestCount(){
		int TotalCount = 0;//试题总数
		String tmp;
		InputStream in = getResources().openRawResource(R.raw.testsubject);
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(in, "gb2312"));// 注意编码
			
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			Log.e("debug", e1.toString());

		}
		try {
			while ((tmp = br.readLine()) != null) {
				TotalCount++;
			}	
			br.close();
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e("debug", e.toString());
		}
		return TotalCount;
		
	}
	/*
	 * 数据转入
	 */
	public void DataTrans() {
		int count = 0;//试题数	
		String tmp, body;
		InputStream in = getResources().openRawResource(R.raw.testsubject);
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(in, "gb2312"));// 注意编码
			
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			Log.e("debug", e1.toString());

		}
		String TESTSUBJECT;
		String TESTANSWER;
		String ANSWERA;
		String ANSWERB;
		String ANSWERC;
		String ANSWERD;
		String IMAGENAME;
		String PROMPTIMAGENAME;
		String ANALYZE;//答案解析

		int TESTTYPE;//题目类型（判断题2、选择题1）
		int TESTBELONG;//章节
		int COURSEID;//课程号
		int POINTSID;//知识点号
		int DIFFICULT;//难易度
		int EXPR1;

		String[] strings = new String[16];
		ContentValues values = new ContentValues();

		try {
			DBAdapter dbAdapter = new DBAdapter(this);
			dbAdapter.open();
			while ((tmp = br.readLine()) != null) {
				strings = tmp.split("`");
				TESTSUBJECT = strings[1].replace("@", "\n");
				TESTANSWER = strings[2];
				COURSEID = Integer.parseInt(strings[3]);
				TESTTYPE = Integer.parseInt(strings[4]);// Dint
				TESTBELONG = Integer.parseInt(strings[5]);// int
				POINTSID = Integer.parseInt(strings[6]);
				DIFFICULT = Integer.parseInt(strings[7]);
				ANSWERA = strings[8].replace("@", "\n");
				ANSWERB = strings[9].replace("@", "\n");
				ANSWERC = strings[10].replace("@", "\n");
				ANSWERD = strings[11].replace("@", "\n");
				IMAGENAME = "image" + strings[12];
				IMAGENAME.replace("-", "_");
				
				PROMPTIMAGENAME = "image" + strings[13];
				PROMPTIMAGENAME.replace("-", "_");
				ANALYZE = strings[14].replace("@", "\n");
				EXPR1 = Integer.parseInt(strings[15]);// integer

				values.clear();
				values.put(DBAdapter.TESTSUBJECT, TESTSUBJECT);
				values.put(DBAdapter.TESTANSWER, TESTANSWER);
				values.put(DBAdapter.COURSEID, COURSEID);
				values.put(DBAdapter.TESTTYPE, TESTTYPE);
				values.put(DBAdapter.TESTBELONG, TESTBELONG);
				values.put(DBAdapter.POINTSID, POINTSID);
				values.put(DBAdapter.DIFFICULT, DIFFICULT);
				values.put(DBAdapter.ANSWERA, ANSWERA);
				values.put(DBAdapter.ANSWERB, ANSWERB);
				values.put(DBAdapter.ANSWERC, ANSWERC);
				values.put(DBAdapter.ANSWERD, ANSWERD);
				values.put(DBAdapter.IMAGENAME, IMAGENAME);
				values.put(DBAdapter.PROMPTIMAGENAME,PROMPTIMAGENAME);
				values.put(DBAdapter.ANALYZE, ANALYZE);
				values.put(DBAdapter.EXPR1, EXPR1);

				dbAdapter.DBInsert(DBAdapter.DATABSE_TABLE_TEST,values);	
				//试题计数
				count ++;
				//设置ProgressDialog 进度条进度
				mProgressDialog.setProgress(count*100/mTotalCount);
				Log.i(tmp, tmp);
			}
			br.close();
			in.close();
			body = "";
			Cursor cursor = dbAdapter.getAllData();
			body += cursor.getCount();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e("debug", e.toString());
		}
	}
	
	/*
	 * CourseID integer primary key autoincrement,"  
    + "CourseName text,SingleAnswer text,MultiAnswer text,FillBlankAnswer text,TrueFalseAnswer text,QuestionsAnswer text,"+
          "DiscussionAnswer text,SynthesisAnswer text,ReserverAnswer text,TotalScore integer,Time integer,IsChoose integer;"
	 */
	public void InitDBCourse(){
		String tmp;
		InputStream in = getResources().openRawResource(R.raw.course);
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(in, "gb2312"));// 注意编码
			
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			Log.e("debug", e1.toString());

		}
		int CourseID;
		String CourseName;
		String SingleAnswer;
		String MultiAnswer;
		String FillBlankAnswer;
		String TrueFalseAnswer;
		String QuestionsAnswer;
		String DiscussionAnswer;
		String SynthesisAnswer;
		String ReserverAnswer;
		int TotalScore;
		int Time;
		int IsChoose;
	
		String[] strings = new String[13];
		ContentValues values = new ContentValues();

		try {
			DBAdapter dbAdapter = new DBAdapter(this);
			dbAdapter.open();
			while ((tmp = br.readLine()) != null) {
				strings = tmp.split("`");
				CourseID = Integer.parseInt(strings[0]);
				CourseName = strings[1];
				SingleAnswer = strings[2];
				MultiAnswer = strings[3];
				FillBlankAnswer = strings[4];
				TrueFalseAnswer = strings[5];
				QuestionsAnswer = strings[6];
				DiscussionAnswer = strings[7];
				SynthesisAnswer  = strings[8];
				ReserverAnswer = strings[9];
				TotalScore = Integer.parseInt(strings[10]);
				Time = Integer.parseInt(strings[11]);
				IsChoose = Integer.parseInt(strings[12]);
				
				values.clear();
				values.put(DBAdapter.COURSEID, CourseID);
				values.put(DBAdapter.COURSENAME, CourseName);
				values.put(DBAdapter.SINGLEANSWER, SingleAnswer);
				values.put(DBAdapter.MULTIANSWER, MultiAnswer);
				values.put(DBAdapter.FILLBLANKANSWER, FillBlankAnswer);
				values.put(DBAdapter.TRUEFALSEANSWER, TrueFalseAnswer);
				values.put(DBAdapter.QUESTIONSANSWER, QuestionsAnswer);
				values.put(DBAdapter.DISCUSSIONANSWER, DiscussionAnswer);
				values.put(DBAdapter.SYNTHESISANSWER, SynthesisAnswer);
				values.put(DBAdapter.RESERVERANSWER, ReserverAnswer);
				values.put(DBAdapter.TOTALSCORE, TotalScore);
				values.put(DBAdapter.TIME, Time);
				values.put(DBAdapter.ISCHOOSE, IsChoose);

				dbAdapter.DBInsert(DBAdapter.DATABSE_TABLE_COURSE,values);	
				Log.i(tmp, tmp);
			}
			br.close();
			in.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e("debug", e.toString());
		}
	}
	
}